# -*- coding: utf-8 -*-

'''
该类用于电流环模拟数据的统计，目前主要用于大屏展示
数据从mongdb中读取
以数据服务的形式将数据从接口传出
'''

from datetime import datetime,timedelta
import pandas as pd
from gov.data_process.data import DataProcess
from pao.data import string_to_date, process_db



class DataProcessStat(DataProcess):
    
    def equip_type(self):
        equip_type=['ax','ay','az','bx','by','bz','cx','cy','cz']
        equip_sx=['小家电','小家电','大家电','小家电','大家电','其他类型','设备机械','其他类型','设备机械']     
        dqsx_df=pd.DataFrame({'equip_type':equip_type,'sets':equip_sx})
        return dqsx_df
    
    def cal_zgl(self, date_now):
        # 计算当前时间点的所有电流环采集的总功率，单位为千瓦
        date_end = string_to_date(date_now)
        list_tep = ''
        def process_func(db):
            nonlocal list_tep
            collection1 = db['shishidata_every_2mins']
            date_s = date_end-timedelta(minutes=2)
            cur = collection1.find({'date': {'$gte': date_s, '$lt': date_end}})
            list_tep = list(cur[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        pd_tep = pd.DataFrame(list_tep)
        res = sum(pd_tep.mean_A.tolist())
        res = res*0.22
        res = round(res, 2)
        return res
    
    def turn_datafrom(self,dataframe,set_sort=None):
        #转换数据形式为，xlabel为一列，其他的系列为一列
        #默认输入数据格式为dataframe,列分别为x轴的值，x轴的标签，系列名及其对于值
        #对于的column name为[x_data,x_label,sets,data]
        maxs=dataframe.groupby('sets').max()
        if set_sort is not None:
            maxs=pd.DataFrame(maxs.sort_values(by='data',ascending=set_sort))
        res_df=dataframe[dataframe['sets']==maxs.index.values[0]].sort_index(by='x_data').reset_index()
        res_df=res_df.rename(columns={'data':maxs.index.values[0]})
        res_df=res_df[['x_label',maxs.index.values[0]]]
        for i in range(1,len(maxs)):
            tep_df=dataframe[dataframe['sets']==maxs.index.values[i]].sort_index(by='x_data').reset_index()
            res_df[maxs.index.values[i]]=tep_df['data'].tolist()
        return res_df
    
    def cal_ydl24_situation(self):
        ydb_list=[]
        #数据获取的时间范围-当前小时的前24小时
        date=datetime.now()+timedelta(hours = -1)
        date_s = date + timedelta(days = -1)
        #获取数据
        def process_func(db):
            nonlocal ydb_list
            collection_ydb=db['ydb']
            cur_ydb=collection_ydb.find({'date': {'$gt': date_s, '$lte': date}})
            ydb_list=list(cur_ydb[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        ydb_df=pd.DataFrame(ydb_list)
        ydbdf=ydb_df.groupby(by=['date']).agg({'datalist':sum}).reset_index()
        ydbdf['x_label']=[x.strftime('%H:%M') for x in ydbdf['date']]
        ydbdf['data']=[round(0.22*x,2) for x in ydbdf['datalist'].tolist()]
        ydbdf=ydbdf.sort_values(by='date')
        res=ydbdf[['x_label','data']].to_json(orient='index',force_ascii=False)
        return res
        
    def cal_dwsx_situation(self):        
        yzb_list=[]
        ydb_list=[]
        #数据获取的时间范围-当前小时的前24小时
        date=datetime.now()+timedelta(hours = -1)
        date_s = date + timedelta(days = -1)
        #获取数据
        def process_func(db):
            nonlocal yzb_list,ydb_list
            collection_yzb=db['yzb']
            collection_ydb=db['ydb']
            cur_yzb=collection_yzb.find({})
            yzb_list=list(cur_yzb[:])
            cur_ydb=collection_ydb.find({'date': {'$gt': date_s, '$lte': date}})
            ydb_list=list(cur_ydb[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        yzb_df=pd.DataFrame(yzb_list)
        ydb_df=pd.DataFrame(ydb_list)
        wy_df=pd.merge(ydb_df,yzb_df,how='left',on='dlh_num')
        wydf=wy_df.groupby(by=['wy_property','date']).agg({'datalist':sum}).reset_index()
        wydf['x_label']=[x.strftime('%H:%M') for x in wydf['date']]
        wydf['data']=[round(0.22*x,2) for x in wydf['datalist'].tolist()]
        wydf=wydf.rename(columns={'wy_property':'sets'})
        wydf=wydf.rename(columns={'date':'x_data'})
        #将获取的数据转为绘图所需格式，并进行排序，包括x轴的数据序列和系列展示顺序
        res_df=self.turn_datafrom(wydf,set_sort=False)
        res=res_df.to_json(orient='index',force_ascii=False)
        return res
    
    def cal_dqsx_situation(self):
        dqsx_df=self.equip_type()
        equip_data=[]
        #数据获取的时间范围-当前小时的前24小时
        date=datetime.now()+timedelta(hours = -1)
        date_s = date + timedelta(days = -1)
        #获取数据
        def process_func(db):
            nonlocal equip_data
            collection_equip=db['analy_equip']
            cur_equip=collection_equip.find({'date': {'$gt': date_s, '$lte': date}})
            equip_data=list(cur_equip[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        equip_df=pd.DataFrame(equip_data)
        dq_data=pd.merge(equip_df,dqsx_df,how='left',on='equip_type')
        dq_df=dq_data.groupby(by=['sets','date']).agg({'meanA':sum}).reset_index()
        dq_df['x_label']=[x.strftime('%H:%M') for x in dq_df['date']]
        dq_df['data']=[round(0.22*x,2) for x in dq_df['meanA'].tolist()]
        dq_df=dq_df.rename(columns={'date':'x_data'})
        #将获取的数据转为绘图所需格式，并进行排序，包括x轴的数据序列和系列展示顺序
        res_df=self.turn_datafrom(dq_df,set_sort=False)
        res=res_df.to_json(orient='index',force_ascii=False)
        return res
        
    def cal_dwsx_analysis(self):
        #数据获取的时间范围-前一天的0-24
        date=datetime.today()+ timedelta(days = -1)
        dates=pd.date_range(date.strftime("%Y-%m-%d"),periods=25,freq='H')
        yzb_list=[]
        ydb_list=[]
        #获取数据
        def process_func(db):
            nonlocal yzb_list,ydb_list
            collection_yzb=db['yzb']
            collection_ydb=db['ydb']
            cur_yzb=collection_yzb.find({})
            yzb_list=list(cur_yzb[:])
            cur_ydb=collection_ydb.find({'date': {'$gte': dates[0], '$lt': dates[-1]}})
            ydb_list=list(cur_ydb[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        yzb_df=pd.DataFrame(yzb_list)
        ydb_df=pd.DataFrame(ydb_list)
        wy_df=pd.merge(ydb_df,yzb_df,how='left',on='dlh_num')
        wydf=wy_df.groupby(by=['wy_property']).agg({'datalist':sum}).reset_index()
        wydf['data']=[round(0.22*x,2) for x in wydf['datalist'].tolist()]
        wydf=wydf[['wy_property','data']]
        wydf=wydf.sort_index(by='data',ascending=False).reset_index(drop=True)
        res=wydf.to_json(orient='index',force_ascii=False)
        return res
        
    def cal_dqsx_analysis(self):
        dqsx_df=self.equip_type()
        equip_data=''
        #数据获取的时间范围-前一天的0-24
        date=datetime.today()+ timedelta(days = -1)
        dates=pd.date_range(date.strftime("%Y-%m-%d"),periods=25,freq='H')
        #获取数据
        def process_func(db):
            nonlocal equip_data
            collection_equip=db['analy_equip']
            cur_equip=collection_equip.find({'date': {'$gte': dates[0], '$lt': dates[-1]}})
            equip_data=list(cur_equip[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        equip_df=pd.DataFrame(equip_data)
        dq_data=pd.merge(equip_df,dqsx_df,how='left',on='equip_type')
        dq_df=dq_data.groupby(by=['sets']).agg({'meanA':sum}).reset_index()
        dq_df['data']=[round(0.22*x,2) for x in dq_df['meanA'].tolist()]
        dq_df=dq_df[['sets','data']]
        dq_df=dq_df.sort_index(by='data',ascending=False).reset_index(drop=True)
        res=dq_df.to_json(orient='index',force_ascii=False)
        return res
     
    def cal_ydjt_analysis(self):
        date=datetime.today()+ timedelta(days = -1)
        dates=pd.date_range(date.strftime("%Y-%m-%d"),periods=25,freq='H')
        ydb_list=[]
        #获取数据
        def process_func(db):
            nonlocal ydb_list
            collection_ydb=db['ydb']
            cur_ydb=collection_ydb.find({'date': {'$gte': dates[0], '$lt': dates[-1]}})
            ydb_list=list(cur_ydb[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        ydb_df=pd.DataFrame(ydb_list)
        ydb_df=ydb_df.groupby(by=['dlh_num']).agg({'datalist':sum}).reset_index()
        ydb_df['data']=[round(0.22*x,2) for x in ydb_df['datalist'].tolist()]
        count_lever=[]
        count_lever.append(len(ydb_df[ydb_df['data']<350]))
        count_lever.append(len(ydb_df[(ydb_df['data']>=350) & (ydb_df['data']<700)]))
        count_lever.append(len(ydb_df[ydb_df['data']>=700]))
        name_jt=['低用电量','中用电量','高用电量']
        res_df=pd.DataFrame({'ydjt':name_jt,'data':count_lever})
        res=res_df.to_json(orient='index',force_ascii=False)
        return res
    
    def cal_gfydl_analysis(self):
        date=datetime.today()+ timedelta(days = -1)
        dates=pd.date_range(date.strftime("%Y-%m-%d"),periods=25,freq='H')
        yzb_list=[]
        ydb_list=[]
        #获取数据
        def process_func(db):
            nonlocal yzb_list,ydb_list
            collection_yzb=db['yzb']
            collection_ydb=db['ydb']
            cur_yzb=collection_yzb.find({})
            yzb_list=list(cur_yzb[:])
            cur_ydb=collection_ydb.find({'date': {'$gte': dates[0], '$lt': dates[-1]}})
            ydb_list=list(cur_ydb[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        yzb_df=pd.DataFrame(yzb_list)
        ydb_df=pd.DataFrame(ydb_list)
        wy_df=pd.merge(ydb_df,yzb_df,how='left',on='dlh_num')
        wy_df['hour']=[i.hour for i in wy_df['date'].tolist()]
        wy_df['sets']=None
        wy_df['sets'] = wy_df.hour.apply(lambda x: '中' if x in [11,12,13,14] else 0)
        cal_df=wy_df[wy_df['sets']=='中']
        wy_df['sets'] = wy_df.hour.apply(lambda x: '早' if x in [6,7,8,9] else 0)
        cal_df=cal_df.append(wy_df[wy_df['sets']=='早'],ignore_index=True)
        wy_df['sets'] = wy_df.hour.apply(lambda x: '晚' if x in [18,19,20,21] else 0)
        cal_df=cal_df.append(wy_df[wy_df['sets']=='晚'],ignore_index=True)
        res_df=cal_df.groupby(by=['sets','wy_property']).agg({'datalist':sum}).reset_index()
        res_df=res_df.rename(columns={'wy_property':'x_label'})
        res_df['data']=[round(0.22*x,2) for x in res_df['datalist'].tolist()]
        res_df['x_data']=res_df['x_label']
        res_df=res_df[['x_data','x_label','data','sets']]
        res_df=self.turn_datafrom(res_df)
        order=['x_label','早','中','晚']
        res_df=res_df[order]
        res=res_df.to_json(orient='index',force_ascii=False)
        return res
    
    def cal_equip_proprietor(self,dlh_num):
        date=datetime.today()
        date_s=date+timedelta(days = -30)
        equip_data=''
        def process_func(db):
            nonlocal equip_data
            collection_equip=db['analy_equip']
            cur_equip=collection_equip.find({'date': {'$gte': date_s, '$lt': date},'dlh_num':dlh_num})
            equip_data=list(cur_equip[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        equip_df=pd.DataFrame(equip_data)
        equip_df=equip_df.groupby(by=['equip_name']).agg({'meanA':sum}).reset_index()
        tep=equip_df['meanA'].tolist()
        equip_df['meanA']=[round(x,2) for x in tep]
        res=equip_df.to_json(orient='index',force_ascii=False)
        return res
    
    def cal_loc_ydl_analysis(self):
        date=datetime.today()+ timedelta(days = -1)
        dates=pd.date_range(date.strftime("%Y-%m-%d"),periods=25,freq='H')
        yzb_list=[]
        ydb_list=[]
        #获取数据
        def process_func(db):
            nonlocal yzb_list,ydb_list
            collection_yzb=db['yzb']
            collection_ydb=db['ydb']
            cur_yzb=collection_yzb.find({})
            yzb_list=list(cur_yzb[:])
            cur_ydb=collection_ydb.find({'date': {'$gte': dates[0], '$lt': dates[-1]}})
            ydb_list=list(cur_ydb[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)
        yzb_df=pd.DataFrame(yzb_list)
        ydb_df=pd.DataFrame(ydb_list)
        loc_df=pd.merge(ydb_df,yzb_df,how='left',on='dlh_num')
        loc_df=loc_df.groupby(by=['loc_longitude','loc_latitude']).agg({'datalist':sum}).reset_index()
        loc_df=loc_df[['loc_longitude','loc_latitude','datalist']]
        tep=loc_df['datalist'].tolist()
        loc_df['datalist']=[round(x,2) for x in tep]
        res=loc_df.to_json(orient='index',force_ascii=False)
        return res
      


        
